import { Breadcrumb, Button, Card, Form, Input, message, Modal, Radio, Space, Upload } from 'antd';
import Channel from 'components/Channel';
import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';

import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

// 4. css-modules修复最小高度问题
import styles from './index.module.scss';
import { UploadOutlined } from '@ant-design/icons';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';
import { editArticleAPI,publicArticleAPI,getArticleById } from 'api/article';
import { useHistory } from 'react-router-dom';
import { useParams } from 'react-router-dom';

//  1. 改造函数式组件
export default function ArticlePublish(_props) {
  // 创建ref
  const formRef =  useRef({})
  const params = useParams()
  console.log('params  ----->  ', params);
  const {id} = params
  console.log('id  ----->  ', id);
  // 声明ref并保存draft
  const draftRef = useRef(false)
  const [type, setType] = useState(1)
  // 1.声明状态
  const [imgUrl, setimgUrl] = useState('')
  // 申明fileList准备驱动试图
  const [fileList, setFileList] = useState([])
  const props = {
    //   设置三个关键属性
    // name代表的时后台接收的文件类型,action代表文件上传的地址接口,设置token
    name: 'image',
    //显示默认支持的文件类型
    accept:'.jpg,.png,.jpeg',
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
    //   if (info.file.status !== 'uploading') {
    //     console.log(info.file, info.fileList);
    //   }
    // console.log('info  ----->  ', info);
        setFileList(info.fileList);
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    // 预览时存储文件url
    onPreview(file){
        console.log('file  ----->  ', file);
        // setimgUrl(file.thumbUrl)
        // 3. 修复预览功能
        setimgUrl(file.url || file.thumbUrl);
    },
    handleCancel(e){
        console.log('e  ----->  ', e);
    },
    // 使用beforeUpload钩子函数
    beforeUpload(file){
        console.log('file  ----->  ', file);
        // 设置白名单
        const whiteList = ['image/jpeg','image/jpg','image/png'];
        // 写上逻辑判断.非图片类型文件,阻止上传
        if(!whiteList.includes(file.type)){
            // 阻止上传.并且不显示在前端界面上
            message.error('文件类型不符合')
            return Upload.LIST_IGNORE
            // 阻止上传,但是会显示在前端界面
            // return false;
        }
    },
    
  };
  const handleValuesChange=(changedValues, allValues) => {
    // console.log('changedValues, allValues  ----->  ', changedValues, allValues);
    if(changedValues.type!== undefined){
      setType(changedValues.type)
    }
  }
  // 新的路由跳转方法: 快速拿history 
  const history = useHistory()
  const loadArticleById = async (id) => {
    const res = await getArticleById(id);
    console.log('res  ----->  ', res);
    // 3. 回填表单数据
    // 🔔setFieldsValue() 给表单字段设置值
    // formRef.current.setFieldsValue({ ...res.data, type: res.data.cover.type });
    const type = res.data.cover.type;
    formRef.current.setFieldsValue({ ...res.data, type });
    // 1. 回填state.type的值
    setType(type);
    // 2. 回填fileList  🔔 string[] 转换为{url: string}[]
    setFileList(res.data.cover.images.map((item) => ({ url: item })));
  };

  // 3. 挂载后，判断，有id就发请求
   useEffect(() => {
    if (id) {
      const res = loadArticleById(id);
      
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  // 点击提交收集formData发送请求
  const handleFinish = async (values) => {
    // console.log(values);
    const formData = {...values}
    if(type===0){
      formData.cover ={
        type: type,
        image: []
      }
    }else{
      formData.cover ={
        type: type,
        image: showFileList.map((item) => {
          // console.log('item.response.data.url  ----->  ', item.response.data.url);
          return  item.response?.data.url|| item.url
        })
      }
    }
    if(fileList.length<type){
      message.error('图片数量不对')
      return
    }
    delete formData.type
    console.log(' formData ----->  ', formData);
    // // 调用Api(再加上draftRef)
    // publicArticleAPI(formData,draftRef.current)

    // 2. 提交时判断调用编辑的API
    if (id) {
      // 🔔 记得传id回去
      await editArticleAPI({ id, ...formData }, draftRef.current);
      message.success('编辑成功', 1);
    } else {
      await publicArticleAPI(formData, draftRef.current);
      message.success('发布成功', 1);
    }
    // 用户提示
    message.success('文章发布成功')
    // 跳转路由
    history.push('/list')
  }
  // 定义计算属性showFileList
  const showFileList = fileList.filter((item,index) => {
    if(type===0) return false;
    if(type===1) return index===0
    if(type===3) return true;
  })
  return (
    <div className={styles.root} style={{ paddingTop: 24 }}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id?'编辑':'新增'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 绑定给form */}
        <Form
          ref={formRef}
          size="large"
          name="basic"
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 20,
          }}
          autoComplete="off"
          onFinish={handleFinish}
          // 💥 富文本设置了name属性要配合初始值
          initialValues={{
            content: '',
            // 1. 默认值
            type: 1,
          }}
          onValuesChange={handleValuesChange}
        >
           <Form.Item
            label="标题"
            name="title"
            // 1.
            rules={[
              {
                required: true,
                message: '请输入文章标题',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="频道"
            name="channel_id"
            // 2.
            rules={[
              {
                required: true,
                message: '请选择频道',
              },
            ]}
          >
            <Channel style={{ width: 200 }}></Channel>
          </Form.Item>

          <Form.Item label="内容" name="content"  
            rules={[
              {
                required: true,
                message: '文章内容不能为空',
              },
              {
                validator: (_, value) => {
                  // 💥 内容为空时，自带空标签，使用自定义校验
                  if (value === '<p><br></p>') {
                    return Promise.reject(new Error('内容不能为空'));
                  }

                  return Promise.resolve();
                },
                message: '文章内容不能为空',
              },
            ]}>
            {/* 3. 受控组件  💥FormItem会自动控制ReactQill为受控组件 */}
            <ReactQuill></ReactQuill>
          </Form.Item>

          <Form.Item label="封面" name="type">
            <Radio.Group>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>


          <Form.Item
            wrapperCol={{
              // 💥 从左向右偏移量
              offset: 4,
              // span: 16,
            }}
          >
          <Form.Item>
            <Upload {...props} listType="picture-card" fileList={showFileList}>
                {/* 根据fileList长度 ,显示上传按钮 */}
              { fileList.length<type && <Button icon={<UploadOutlined />}></Button>}
              {/* visible:对话框是否可见(!!表示布尔类型强制转换) */}
              {/* 使用modal组件显示url */}
              </Upload>
              
          </Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {id?'编辑':'新增'}文章
              </Button>

              <Button type="primary" htmlType="submit" onClick={()=>{draftRef.current=true;}}>
                存草稿
              </Button>
            </Space>
          </Form.Item>
         
        </Form>
      </Card>
      <Modal title="图片预览" visible={!!imgUrl} footer={null} style={{textAlign: 'center'}} >
              <img width="400" src={imgUrl} alt="" />
      </Modal>
    </div>
  );
}
